<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" @input="changeInput" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" />
        <!-- 树形组件 -->
        <el-tree ref="department" node-key="id" :data="departmentList" :props="defaultProps" highlight-current default-expand-all
          :expand-on-click-node="false"
          @current-change="handleNodeClick"
          ></el-tree>
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')" >添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmlployeeList">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto"></el-avatar>
              <span v-else style="background-color: #2f9ee9; width: 40px; height: 40px;  border-radius: 50%;display: inline-block; font-size: 18px; line-height: 40px;  color: #fff;">{{ row.username.split('').length >= 4 ? row.username[2]: row.username[0] }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column  prop='mobile' label="手机号" sortable></el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable></el-table-column>
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门"></el-table-column>
          <el-table-column prop="timeOfEntry" label="入职时间"></el-table-column>
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button> 
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
              title="确定删除本行内容吗？"
              @onConfirm="confirmDel(row.id)"
            >
              <el-button type="text" size="mini" slot="reference" style="margin-left: 10px;">删除</el-button>
            </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <ImportExcel @uploadSuccess=" getDefalutEmployee" :showExcelDialog.sync="showExcelDialog"></ImportExcel>
        <!-- 分页 -->
        <el-row type="flex" justify="end" height="60px" align="middle">
          <el-pagination
          layout="total, prev, pager, next"
          :total=" total"
          :current-change="queryParams.page"
          :page-size="queryParams.pageSize"
          @current-change="changePages"
          >
          </el-pagination>
        </el-row>

        <!-- 弹出层 -->
        <el-dialog :visible.sync="showRoleDioalog" title="分配权限">
          <el-checkbox-group v-model="roleIds">
            <el-checkbox v-for="item in eabledRoleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
          
          <el-row type="flex" justify="center" slot="footer" >
              <el-button  size="mini" type="primary" @click="btnSubmit">确定</el-button>
              <el-button size="mini" @click="cancel">取消</el-button>
          </el-row>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {getDepartmentList} from '@/api/department'
import {getEmployeeList, exportEmplpyee, delEmployee, assignRole, getEmployeeDetail, getRoleList} from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel  from './components/import-excecl'
import { get } from 'js-cookie'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      departmentList: [],
      defaultProps: {
          children: 'children',
          label: 'name'
        },
        // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1,
        pageSize: 10,
        keyword: ''
      },
      list: [],
      total: 0,
      showExcelDialog: false,
      showRoleDioalog: false,
      eabledRoleList: [],
      currentUserId: '',
      roleIds: []
    }
  },
  methods: {
    async getdepartmentList() {
      this.departmentList = this.formatData(await getDepartmentList(), 0)
      this.queryParams.departmentId = this.departmentList[0].id

      this.$nextTick(() => {
        this.$refs.department.setCurrentKey(this.queryParams.departmentId)
        this.getDefalutEmployee()
      })
    },
    // 格式数据
    formatData(data,index) {
      let arr = []
      data?.forEach(item => {
        if (item.pid === index) {
          arr.push(item)
          item.children = this.formatData(data,item.id)
        }
      })
      return arr
    },
    handleNodeClick(data) {
      this.queryParams.departmentId = data.id
      this.queryParams.page = 1
      this.getDefalutEmployee()
    },

    // 获取默认的员工数据
    async getDefalutEmployee() {
      const res = await getEmployeeList(this.queryParams)
    // console.log(res);
    this.list = res.rows
    this.total = res.total
    
    },
    // 切换页码
    changePages(page) {
      this.queryParams.page = page
      this.getDefalutEmployee()
    },
    // 搜索查询
    changeInput() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getDefalutEmployee()
      },300)
      
    },

    // 导出员工
    async exportEmlployeeList() {
      const res = await exportEmplpyee()
      // console.log(res.type); 
      // 使用一个npm 包将文件下载到浏览器 file-saver
      FileSaver.saveAs(res, '员工信息表.xlsx')
      this.$message.success('导出成功')
    },
    // 删除员工
    async confirmDel(id) {
      // alert(id)
      // 删除员工
      await delEmployee(id)
      this.$message.success('删除成功')
      // 判断当前删除数据是否为每页最后一条数据，如果是，则删除后需要渲染前一页数据
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
        this.getDefalutEmployee()
      }
      else {
        this.getDefalutEmployee()
      }
      

    },
    // 分配角色
    async btnRole(id) {
      const res = await getRoleList()
      console.log(res);
      this.eabledRoleList = res 
      this.currentUserId = id
      const {roleIds} = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDioalog = true

    },
    cancel() {
      this.showRoleDioalog = false
    },

    // 点击确定
    async btnSubmit() {
      // 调用接口上传权限
      const res = await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds})
        this.$message.success("角色分配成功")
        this.showRoleDioalog = false
    }
  },
  created() {
    this.getdepartmentList()

  }
  
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
      
    }
  }
}

</style>